<template>
  <div class="ads-img">
    <el-upload
      class="avatar-uploader"
      :action="''"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :http-request="customUpload"
      :before-upload="beforeAvatarUpload"
      :limit="limit"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      <el-progress
        type="circle"
        :percentage="uploadPercentage"
        status="success"
        v-show="isShowProgress"
      ></el-progress>
    </el-upload>
  </div>
</template>

<script>
import { uploadImg } from '@/service/course'
export default {
  data () {
    return {
      imageUrl: '',
      uploadPercentage: 0,
      isShowProgress: false,
      isLoaded: false
    }
  },
  props: {
    value: {
      type: String
    },
    limit: {
      type: Number,
      default: 1
    }
  },
  watch: {
    value (newValue) {
      if (!this.isLoaded) {
        this.imageUrl = newValue
        this.isLoaded = true
      }
    }
  },
  methods: {
    //   自定义图片上传函数
    async customUpload (option) {
      // console.log(option)
      const fd = new FormData()
      fd.append('file', option.file)
      this.isShowProgress = true
      const { data } = await uploadImg(fd, e => {
        this.uploadPercentage = (e.loaded / e.total).toFixed(2) * 100
      })
      //   console.log(data)
      if (data.code === '000000') {
        this.isShowProgress = false
        // 上传成功后进度条清零
        this.uploadPercentage = 0
        this.$emit('input', data.data.name)
      }
    },
    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
::v-deep .el-progress--circle,
.el-progress--dashboard {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
.el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
